package com.traveling.hztraveling.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.traveling.hztraveling.context.BaseContext;
import com.traveling.hztraveling.entity.po.HzCulture;
import com.traveling.hztraveling.entity.vo.CalendarEvent;
import com.traveling.hztraveling.entity.vo.Result;
import com.traveling.hztraveling.mapper.HzCultureMapper;
import com.traveling.hztraveling.service.IHzCultureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LHD
 * @since 2025-05-29
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class HzCultureServiceImpl extends ServiceImpl<HzCultureMapper, HzCulture> implements IHzCultureService {


    @Override
    @Transactional
    public Result<HzCulture> addCulture(HzCulture hzCulture){
        if (BaseContext.getCurrentId()!=null){
            hzCulture.setUserId(Math.toIntExact(BaseContext.getCurrentId()));
        }


        // 校验工作，不可重复添加
        Integer userId = hzCulture.getUserId();
        String activity = hzCulture.getActivity();
        LocalDate date = hzCulture.getDate();
        List<HzCulture> cList = this.lambdaQuery()
                .eq(HzCulture::getUserId, userId)
                .list();
        for (HzCulture c : cList) {
            if (c != null && c.getActivity().equals(activity) && c.getDate().equals(date)){
                if (c.getStatus()!=null&&c.getStatus().equals("pending")){
                    return Result.fail("同一用户不可重复下单");
                }
                else if (c.getStatus().equals("certain")){
                    return Result.fail("该订单已经完成");
                }
            }
        }


        hzCulture.setStatus("pending");
        hzCulture.setCreateTime(LocalDateTime.now());
        int insert = this.baseMapper.insert(hzCulture);
        if ( insert > 0){
            return Result.success(hzCulture);
        }
        else {
            throw  new RuntimeException("添加失败");
        }
    }

    @Override
    public Result<List<CalendarEvent>> calendar(Integer year,Integer month){
        Integer userId = Math.toIntExact(BaseContext.getCurrentId());
        LocalDate beginDate = LocalDate.of(year, month, 1);
        if (beginDate.getMonthValue() == 12){
            beginDate = beginDate.plusYears(1);
        }
        if (beginDate.getMonthValue() == 1){
            beginDate = beginDate.minusYears(1);
        }
         LocalDate endDate = beginDate.plusMonths(1);

        List<CalendarEvent> calendarEvents = new ArrayList<>();
        this.lambdaQuery()
                .eq( HzCulture::getUserId, userId)
                .in(HzCulture::getStatus, "pending")
                .le(HzCulture::getDate, endDate)
                .ge(HzCulture::getDate, beginDate)
                .list()
                .forEach(c -> {
                    CalendarEvent calendarEvent = new CalendarEvent(c.getDate().getYear(), c.getDate().getMonthValue(), c.getDate().getDayOfMonth());
                    calendarEvents.add(calendarEvent);
                });
        return Result.success(calendarEvents);
    }

    @Override
    public Page<HzCulture> getOrders(Integer page, Integer pageSize, String status){
        if (BaseContext.getCurrentId()==null){
            // 管理端查询全部
            Page<HzCulture> page1 = new Page<>( page, pageSize);
            if (status == null){
                return this.lambdaQuery()
                        .page(page1);
            }
            if (status.equals( "all")){
                return this.lambdaQuery()
                        .page( page1);
            }
            else {
                return this.lambdaQuery()
                        .eq(HzCulture::getStatus, status)
                        .page(page1);
            }
        }
        Integer userId = Math.toIntExact(BaseContext.getCurrentId());
         Page<HzCulture> page1 = new Page<>( page, pageSize);
        if (status == null){
            return this.lambdaQuery()
                    .eq(HzCulture::getUserId, userId)
                    .page(page1);
        }
        if (status.equals( "all")){
            return this.lambdaQuery()
                    .eq(HzCulture::getUserId, userId)
                    .page( page1);
        }
        else {
             return this.lambdaQuery()
                    .eq(HzCulture::getUserId, userId)
                    .eq(HzCulture::getStatus, status)
                    .page(page1);
        }
    }

    @Override
    public Page<HzCulture> getOrders(int i, int i1, Object o, String keyword){

        Integer userId = Math.toIntExact(BaseContext.getCurrentId());
        Page <HzCulture> page = new Page<>( i, i1);

        if (keyword.chars().anyMatch((Character::isDigit))){
             return this.lambdaQuery()
                     .eq(HzCulture::getUserId ,userId )
                    .eq(HzCulture::getId, keyword)
                    .page( page);
        }else{
            String activity1 = "汉服体验";
            String activity2 = "书法体验";
            String  activity3 = "茶艺体验";
            String activity4 = "美食制作";
            if (activity1.contains(keyword)){
                keyword = "hanfu";
            }
             if (activity2.contains(keyword)){
                keyword = "calligraphy";
            }
             if (activity3.contains(keyword)){
                  keyword = "tea";
             }
              if (activity4.contains(keyword)){
                 keyword = "food";
             }
             return this.lambdaQuery()
                    .eq(HzCulture::getUserId ,userId )
                    .like(HzCulture::getActivity, keyword)
                    .page(page);
        }
    }

    @Override
    @Transactional
    public HzCulture getRefund(Integer orderId){
        Integer userId = Math.toIntExact(BaseContext.getCurrentId());
        HzCulture hzCulture = this.lambdaQuery()
                .eq(HzCulture::getId, orderId)
                .eq(HzCulture::getUserId, userId)
                .eq( HzCulture::getStatus, "pending")
                .one();
         if (hzCulture == null){
            throw new RuntimeException("该订单不存在或已被取消");
        }
         hzCulture.setStatus("refund");
         this.updateById(hzCulture);
         return hzCulture;
    }

}
